import sensor from '@ohos.sensor';
import { BasicNetworkUtil } from '../network/BasicNetworkUtil';
import { FlightGearDecoder } from '../NetWork/DecodeImpl/FlightGearDecode';
import { BasicDataEncoder } from './BasicDataEncoder';
import { FlightGearDataEncoder } from './Impl/FlightGearDataEncoder';

let x = 0; //舵机
let y = 0; //升降舵
let z = 0; //aileron

export class Info {
  x: number;
  y: number;
  z: number;

  constructor(x: number = 0, y: number = 0, z: number = 0) {
    this.x = x;
    this.y = y;
    this.z = z;
  }

  public static fromObject(obj: Object): Info {
    if (obj.hasOwnProperty("x") && obj.hasOwnProperty("y") && obj.hasOwnProperty("z")) {
      return new Info(obj['x'], obj['y'], obj['z']);
    } else {
      return null;
    }
  }

  public static fromString(str: string): Info {
    return Info.fromObject(JSON.parse(str));
  }

  public toObject(): Object {
    return { x: this.x, y: this.y, z: this.z };
  }

  public toString(): string {
    return JSON.stringify(this.toObject());
  }

  public encode() {
    return FlightGearDataEncoder.encode(this);
  }
}

export class GyroscopeControl {
  private callback: (list: Info) => void;
  private num: number;

  constructor(interval: number) {
    sensor.on(sensor.SensorId.GYROSCOPE, (data) => {
      x += data.x * interval / 1e8 * 2;
      y += data.y * interval / 1e8 * 2;
      z -= data.z * interval / 1e8 * 2;
    }, { interval: interval });
    this.num = setInterval(() => {
      if (this.callback != null || this.callback != undefined) {
        let info = new Info();
        info.x = x;
        info.y = y;
        info.z = z;
        this.callback(info);
      }
    }, 20);
  }

  public setCallback(func: (list: Info) => void) {
    this.callback = func;
  }

  public async close() {
    clearInterval(this.num);
    sensor.off(sensor.SensorId.GYROSCOPE);
    x = 0;
    y = 0;
    z = 0;
    let info = new Info();
    info.x = x;
    info.y = y;
    info.z = z;
    this.callback(info);
  }
}